<?php

class Cms_UserController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        $auth = Zend_Auth::getInstance();
        
        if ($auth->hasIdentity()) {
            $this->view->identity = $auth->getIdentity();
        }
    }

    public function createAction()
    {
        $userForm = new Cms_Form_User();
        if($this->_request->isPost()) {
            if ($userForm->isValid($_POST)) {
                // Get the posts values
                $nome = $userForm->getValue('userNome');
                $email = $userForm->getValue('userEmail');
                //$role = $userForm->getValue('userRole');
                $password = $userForm->getValue('userPassword');
                // Create user
                $usersModel = new Cms_Model_Users;
                $rowUser = $usersModel->createUser($nome, $email, $password, 'user');
                
                //Invio mail se utente creato
                if ($rowUser != NULL) {
                    $mail = new Zend_Mail();
                    CMS_Mail::sendConfirmUserMail(
                                $mail, 
                                'info@ilbivacco-toscana.it', 
                                'Associazione il bivacco', 
                                $email, 
                                $nome, 
                                $password
                            );
                }

                // Go to the home whith flashMessage
                $this->_helper->flashMessenger->addMessage('Utente Creato con successo!');
                $this->_redirect('/');
                
                // Go to user list
                //return $this->_forward('list', 'user', 'cms');
            }
        }
        $userForm->setAction('/cms/user/create');
        $this->view->form = $userForm;
    }

    public function listAction()
    {
        $currentUsers = Cms_Model_Users::getUsers();
        if ($currentUsers->count() > 0) {
            $this->view->users = $currentUsers;
        } else {
            $this->view->users = NULL;  
        }
        
        // Imposto il messaggio flash che viene da /cms/user/delete
        $this->view->messages = $this->getHelper('FlashMessenger')->getMessages();
    }
    public function updateAction()
    {
        $userForm = new Cms_Form_User;
        $userForm->setAction('/cms/user/update');
        $userForm->removeElement('userPassword');
        $userForm->removeElement('userRole');
        $user = new Cms_Model_Users();
        
        if ($this->_request->isPost()) {
            if ($userForm->isValid($_POST)) {
                $id = $userForm->getValue('userId');
                $nome = $userForm->getValue('userNome');
                $email = $userForm->getValue('userEmail');
                //$role = $userForm->getValue('userRole');
                $user->updateUser($id, $nome, $email, 'user');
                
                // Go to the user list whith flashMessage
                $this->_helper->flashMessenger->addMessage('Utente modificato con successo!');
                $this->_redirect('/cms/user/list');
            }
        } else {
            $id = $this->_request->getParam('id');
            $currentUser = $user->getUserById($id);
            $userForm->populate($currentUser->toArray());
        }
        $this->view->form = $userForm;
    }

    public function passwordAction()
    {
        $passwordForm = new Cms_Form_User;
        $passwordForm->setAction('/cms/user/password');
        $passwordForm->removeElement('userNome');
        $passwordForm->removeElement('userEmail');
        $passwordForm->removeElement('userRole');
        
        $userModel = new Cms_Model_Users();
        if ($this->_request->isPost()) {
            if ($passwordForm->isValid($_POST)) {
                $id = $passwordForm->getValue('userId');
                $password = $passwordForm->getValue('userPassword');
                $rowUser = $userModel->updatePassword($id, $password);
                //Invio mail conferma nuova password
                if ($rowUser != NULL) {
                    $mail = new Zend_Mail();
                    CMS_Mail::sendConfirmNewPwdMail(
                                $mail, 
                                'info@ilbivacco-toscana.it', 
                                'Associazione il bivacco', 
                                $rowUser->userEmail, 
                                $rowUser->userNome, 
                                $password
                            );
                }
                // Go to the user list whith flashMessage
                $this->_helper->flashMessenger->addMessage('Password modificata con successo!');
                return $this->_redirect('/cms/user/list');
            }
        } else {
            $id = $this->_request->getParam('id');
            $curreneUser = $userModel->getUserById($id);
            $passwordForm->populate($curreneUser->toArray());
        }
        
        $this->view->form = $passwordForm;
    }
    
    public function deleteAction()
    {
        $id = $this->_getParam('id');
        $userModel = new Cms_Model_Users();
        $userModel->deleteUser($id);
        
        // Go to the user list whith flashMessage
        $this->_helper->flashMessenger->addMessage('Utente cancellato con successo!');
        $this->_redirect('/cms/user/list');
    }

    public function loginAction()
    {
        $userForm = new Cms_Form_User;
        $userForm->setAction('/cms/user/login');
        $userForm->removeElement('userNome');
        $userForm->removeElement('userRole');
        $userForm->removeElement('captcha');
        $userForm->getElement('submit')->setLabel('Login');
        
        if ($this->_request->isPost() && $userForm->isValid($_POST)) {
            $data = $userForm->getValues();
            
            // **Setup auth adapter**
            // Get the default Db adapter
            $db = Zend_Db_Table::getDefaultAdapter();
            // Create auth adapter
            $authAdapter = new Zend_Auth_Adapter_DbTable(
                        $db, 
                        'users', 
                        'userEmail', 
                        'userPassword'
                    );
            // Set the username and password
            $authAdapter->setIdentity($data['userEmail']);
            $authAdapter->setCredential(md5($data['userPassword']));
            // Authenticate
            $result = $authAdapter->authenticate();
            if ($result->isValid()) {
                // Store 
                $auth = Zend_Auth::getInstance();
                $storage = $auth->getStorage();
                $storage->write($authAdapter->getResultRowObject(array(
                    'userId',
                    'userEmail',
                    'userNome',
                    'userRole',
                )));
                return $this->_forward('index');
            } else {
                $this->view->loginMessage = "Attenzione! Email o password non corrette.";
            }
        }
        $this->view->form = $userForm;
    }
    
    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
    }
    
    public function showAction()
    {
        try {
                $id = $this->_getParam('id');
                $userModel = new Cms_Model_Users();
                $this->view->user = $userModel->getUserById($id);
            } catch (Zend_Exception $e) {
                $this->view->message = $e->getMessage();
            }
    }
}







